import React from 'react';
import {Table, Card} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PERMISSION, formatPrintExcelUrl, formatPrintPdfUrl} from './constants';
import {hasPermissions} from './utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {partSaleOrderTrackStatus, transportType, partOrderPriceTerms, paymentType, currency} from '../Enum';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATETIME_FORMAT} from '../constants';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onPrintExcel = e => {
        e.stopPropagation();
        window.open(formatPrintExcelUrl(e.currentTarget.dataset.partOrderPIId));
    }
    onPrintPdf = e => {
        e.stopPropagation();
        window.open(formatPrintPdfUrl(e.currentTarget.dataset.partOrderPIId));
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.brandName',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandName',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'brandName' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '备件订单号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
            render: (text, record) => <Link key="detail" to={routes.detail.format(record.partOrderId)}>{text}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partOrderTypeName',
                defaultMessage: '订单类型'
            }),
            dataIndex: 'partOrderTypeName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.partOrderPriceTerms',
                defaultMessage: '价格条款'
            }),
            dataIndex: 'partOrderPriceTerms',
            render: text => conventEnumValueToString(partOrderPriceTerms, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.paymentType',
                defaultMessage: '付款方式'
            }),
            dataIndex: 'paymentType',
            render: text => conventEnumValueToString(paymentType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.transportType',
                defaultMessage: '运输方式'
            }),
            dataIndex: 'transportType',
            render: text => conventEnumValueToString(transportType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.varietyQuantity',
                defaultMessage: '品种'
            }),
            dataIndex: 'varietyQuantity'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalQuantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'totalQuantity'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalAmount',
                defaultMessage: 'PI总金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.fobTotalAmount',
                defaultMessage: 'FOB金额'
            }),
            dataIndex: 'fobTotalAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.shipmentAmount',
                defaultMessage: '运费'
            }),
            dataIndex: 'shipmentAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.insuranceAmount',
                defaultMessage: '保险费'
            }),
            dataIndex: 'insuranceAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.submitTime',
                defaultMessage: '提报日期'
            }),
            dataIndex: 'submitTime',
            render: text => formatDateTime(text, DATETIME_FORMAT),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'submitTime' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.creditAuditedTime',
                defaultMessage: '付款日期'
            }),
            dataIndex: 'creditAuditedTime',
            render: text => formatDateTime(text, DATETIME_FORMAT),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'creditAuditedTime' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '订单状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(partSaleOrderTrackStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: 'PI生成时间'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.confirmTime',
                defaultMessage: 'PI确认时间'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATETIME_FORMAT),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'confirmTime' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.stockCreateTime',
                defaultMessage: '备货上传SAP日期'
            }),
            dataIndex: 'stockCreateTime',
            render: text => formatDateTime(text, DATETIME_FORMAT),
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'stockCreateTime' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalQuantityInvoice',
                defaultMessage: '发运数量'
            }),
            dataIndex: 'totalQuantityInvoice'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.itemCountInvoice',
                defaultMessage: '发运品种'
            }),
            dataIndex: 'itemCountInvoice'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalAmountInvoice',
                defaultMessage: '发运金额'
            }),
            dataIndex: 'totalAmountInvoice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.stockQuantity',
                defaultMessage: '备货数量'
            }),
            dataIndex: 'stockQuantity'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.stockItem',
                defaultMessage: '备货品种'
            }),
            dataIndex: 'stockItem'
        }, {
            title: formatMessage({
                id: 'tablePanel.column.stockMoney',
                defaultMessage: '备货金额'
            }),
            dataIndex: 'stockMoney',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.printExcel,
                        children: (
                            <a key="printExcel" data-id={r.id} onClick={this.onPrintExcel}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.printExcel',
                                    defaultMessage: '下载Excel'
                                })}
                            </a>
                        ),
                        hidden: !hasPermissions(this.props.permissions, PERMISSION.printExcel)
                    }, {
                        id: PERMISSION.printPdf,
                        children: (
                            <a key="printPdf" data-id={r.id} onClick={this.onPrintPdf}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.printPdf',
                                    defaultMessage: '下载PDF'
                                })}
                            </a>
                        ),
                        hidden: !hasPermissions(this.props.permissions, PERMISSION.printPdf)
                    }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        if(!this.props.isDealerUser)
            columns.splice(2, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代ERP号'
                    }),
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                    dataIndex: 'dealerCode',
                }, {
                    title: formatMessage({
                        id: 'tablePanel.column.customerOrderCode',
                        defaultMessage: '客户订单号'
                    }),
                    dataIndex: 'customerOrderCode',
                },
            ]);
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    isDealerUser: state.getIn(['page', 'domainData', 'init', 'isDealerUser']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
